//package com.xiefengf.elasticsearch_client;
//
//import cn.hutool.json.JSONUtil;
//import org.apache.http.HttpHost;
//import org.elasticsearch.action.bulk.BulkRequest;
//import org.elasticsearch.action.bulk.BulkResponse;
//import org.elasticsearch.action.delete.DeleteRequest;
//import org.elasticsearch.action.delete.DeleteResponse;
//import org.elasticsearch.action.get.GetRequest;
//import org.elasticsearch.action.get.GetResponse;
//import org.elasticsearch.action.index.IndexRequest;
//import org.elasticsearch.action.index.IndexResponse;
//import org.elasticsearch.action.search.SearchRequest;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.action.update.UpdateRequest;
//import org.elasticsearch.action.update.UpdateResponse;
//import org.elasticsearch.client.RequestOptions;
//import org.elasticsearch.client.RestClient;
//import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.common.unit.Fuzziness;
//import org.elasticsearch.common.xcontent.XContentType;
//import org.elasticsearch.index.query.*;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.SearchHits;
//import org.elasticsearch.search.aggregations.AggregationBuilders;
//import org.elasticsearch.search.builder.SearchSourceBuilder;
//import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
//import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
//import org.elasticsearch.search.sort.SortOrder;
//import org.junit.jupiter.api.Test;
//
//import java.io.IOException;
//import java.util.Arrays;
//import java.util.Map;
//
///**
// * @author xiefengf
// * @version 1.0
// * @date 2024/3/20 21:55
// * <p>
// * 文档（doc）增删改查
// */
//public class Doc {
//
//    /**
//     * 创建ES客户端
//     *
//     * @return
//     */
//    public RestHighLevelClient createClient() {
//        return new RestHighLevelClient(RestClient.builder(new HttpHost("124.220.215.81", 9200, "http")));
//    }
//
//    /**
//     * 关闭ES客户端
//     *
//     * @param client
//     */
//    public void closeClient(RestHighLevelClient client) {
//        try {
//            client.close();
//        } catch (IOException e) {
//            System.out.println("关闭客户端失败");
//        }
//    }
//
//    /**
//     * 根据文档id查询文档
//     */
//    @Test
//    public void getDocById() throws IOException {
//        // 创建客户端
//        RestHighLevelClient client = createClient();
//        // 新增文档 - 请求对象
//        GetRequest request = new GetRequest();
//        // 设置文档唯一标识
//        request.index("user").id("1002");
//        // 查询
//        GetResponse response = client.get(request, RequestOptions.DEFAULT);
//        // 输出结果
//        System.out.println("_index:" + response.getIndex());
//        System.out.println("_type:" + response.getType());
//        System.out.println("_id:" + response.getId());
//        System.out.println("source:" + response.getSourceAsString());
//        // 关闭客户端
//        closeClient(client);
//    }
//
//    /**
//     * 查询全部文档
//     */
//    @Test
//    public void getDocList() throws IOException {
//        // 创建客户端
//        RestHighLevelClient client = createClient();
//        // 搜索文档 - 请求对象
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//
//        // 构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        // 查询所有数据
//        sourceBuilder.query(QueryBuilders.matchAllQuery());
//
//        // 查询
//        request.source(sourceBuilder);
//        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//        // 输出结果
//        SearchHits hits = response.getHits();
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("========>>");
//        for (SearchHit hit : hits) {
//        //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//        }
//        System.out.println("<<========");
//        // 关闭客户端
//        closeClient(client);
//    }
//
//    /**
//     * 高级查询文档（分页/条件/字段）
//     *
//     * @throws IOException
//     */
//    @Test
//    public void getDocByCondition() throws IOException {
//        // 创建客户端
//        RestHighLevelClient client = createClient();
//        // 搜索文档 - 请求对象
//        SearchRequest request = new SearchRequest();
//        request.indices("user");
//
//
//
//        // 1、构建查询的请求体
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        // 2、普通条件查询
//        TermQueryBuilder termQuery = QueryBuilders.termQuery("age", "20");
//        sourceBuilder.query(termQuery);
//        // 3、分页查询（from-页码 size每页大小）
//        sourceBuilder.from(0);
//        sourceBuilder.size(2);
//        // 4、数据排序查询
//        sourceBuilder.sort("age", SortOrder.DESC);
//        // 5、查询字段过滤
//        String[] excludes = {};
//        String[] includes = {"name", "age"};
//        sourceBuilder.fetchSource(includes, excludes);
//        // 6、Bool查询（must-必须包含、mustNot-一定不含，should-可能包含）
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        boolQueryBuilder.must(QueryBuilders.matchQuery("age", "20"));
//        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "黑大帅"));
//        boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
//        sourceBuilder.query(boolQueryBuilder);
//        // 7、范围查询（gte-大于等于，lt-小于）
//        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
//        rangeQuery.gte("20");
//        rangeQuery.lt("20");
//        sourceBuilder.query(rangeQuery);
//        // 8、模糊查询
//        sourceBuilder.query(QueryBuilders.fuzzyQuery("name","黑大").fuzziness(Fuzziness.ONE));
//        // 9、高亮字段设置
//        HighlightBuilder highlightBuilder = new HighlightBuilder();
//        highlightBuilder.preTags("<font color='red'>");//设置标签前缀
//        highlightBuilder.postTags("</font>");//设置标签后缀
//        highlightBuilder.field("name");//设置高亮字段
//        sourceBuilder.highlighter(highlightBuilder);
//        // 10、聚合查询
//        sourceBuilder.aggregation(AggregationBuilders.avg("avgAge").field("age"));
//        // 11、分组统计
//        sourceBuilder.aggregation(AggregationBuilders.terms("age_group_by").field("age"));
//
//
//
//        // 查询
//        request.source(sourceBuilder);
//        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//        // 输出结果
//        SearchHits hits = response.getHits();
//        System.out.println("response:" + response);
//        System.out.println("took:" + response.getTook());
//        System.out.println("timeout:" + response.isTimedOut());
//        System.out.println("total:" + hits.getTotalHits());
//        System.out.println("MaxScore:" + hits.getMaxScore());
//        System.out.println("========>>");
//        for (SearchHit hit : hits) {
//            //输出每条查询的结果信息
//            System.out.println(hit.getSourceAsString());
//            //打印高亮结果
//            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
//            System.out.println(highlightFields);
//        }
//        System.out.println("<<========");
//        // 关闭客户端
//        closeClient(client);
//    }
//
//    /**
//     * 创建文档
//     */
//    @Test
//    public void saveDoc() throws IOException {
//        // 创建客户端
//        RestHighLevelClient client = createClient();
//        // 新增文档 - 请求对象
//        IndexRequest request = new IndexRequest();
//        // 设置文档唯一标识
//        request.index("user").id("1002");
//        // 创建数据对象
//        User user = new User("美羊羊", 20, "女性");
//        // 转为JSON字符串
//        String userStr = JSONUtil.toJsonStr(user);
//        // 添加文档数据，数据格式指定为JSON
//        request.source(userStr, XContentType.JSON);
//        // 客户端发送请求，获取响应对象
//        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//        // 输出结果
//        System.out.println("_index:" + response.getIndex());
//        System.out.println("_id:" + response.getId());
//        System.out.println("_result:" + response.getResult());
//        // 关闭客户端
//        closeClient(client);
//    }
//
//    /**
//     * 批量创建文档
//     */
//    @Test
//    public void saveBatchDoc() throws IOException {
//        // 创建客户端
//        RestHighLevelClient client = createClient();
//        // 批量新增文档 - 请求对象
//        BulkRequest request = new BulkRequest();
//        request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "慢羊羊","age",20,"sex","女"));
//        request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "红太狼","age",27,"sex","女"));
//        request.add(new IndexRequest().index("user").id("1007").source(XContentType.JSON, "name", "小灰灰","age",5,"sex","男"));
//        request.add(new IndexRequest().index("user").id("1008").source(XContentType.JSON, "name", "蕉太狼","age",23,"sex","男"));
//        request.add(new IndexRequest().index("user").id("1009").source(XContentType.JSON, "name", "村长","age",60,"sex","男"));
//        request.add(new IndexRequest().index("user").id("1010").source(XContentType.JSON, "name", "刀狼","age",50,"sex","男"));
//        // 客户端发送请求，获取响应对象
//        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
//        // 输出结果
//        System.out.println("_index:" + response.getTook());
//        System.out.println("_id:" + Arrays.toString(response.getItems()));
//        // 关闭客户端
//        closeClient(client);
//    }
//
//    /**
//     * 更新文档
//     */
//    @Test
//    public void updateDoc() throws IOException {
//        // 创建客户端
//        RestHighLevelClient client = createClient();
//        // 更新文档 - 请求对象
//        UpdateRequest request = new UpdateRequest();
//        // 设置文档唯一标识
//        request.index("user").id("1001");
//        // 设置需要修改的数据
//        request.doc(XContentType.JSON, "name", "潇洒哥");
//        // 客户端发送请求，获取响应对象
//        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
//        // 输出结果
//        System.out.println("_index:" + response.getIndex());
//        System.out.println("_id:" + response.getId());
//        System.out.println("_result:" + response.getResult());
//        // 关闭客户端
//        closeClient(client);
//    }
//
//    /**
//     * 删除文档
//     */
//    @Test
//    public void deleteDoc() throws IOException {
//        // 创建客户端
//        RestHighLevelClient client = createClient();
//        // 更新文档 - 请求对象
//        DeleteRequest request = new DeleteRequest();
//        // 设置文档唯一标识
//        request.index("user").id("1001");
//        // 客户端发送请求，获取响应对象
//        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
//        // 输出结果
//        System.out.println(response.toString());
//        // 关闭客户端
//        closeClient(client);
//    }
//
//    /**
//     * 批量删除文档
//     */
//    @Test
//    public void deleteBatchDoc() throws IOException {
//        // 创建客户端
//        RestHighLevelClient client = createClient();
//        // 批量新增文档 - 请求对象
//        BulkRequest request = new BulkRequest();
//        request.add(new DeleteRequest().index("user").id("1003"));
//        request.add(new DeleteRequest().index("user").id("1004"));
//        // 客户端发送请求，获取响应对象
//        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
//        // 输出结果
//        System.out.println("_index:" + response.getTook());
//        System.out.println("_id:" + Arrays.toString(response.getItems()));
//        // 关闭客户端
//        closeClient(client);
//    }
//
//}
